package com.caregiver.watch.business.user.service.impl;

import com.caregiver.watch.business.user.model.dto.SendSmsCodeParam;
import com.caregiver.watch.business.user.model.dto.VerifySmsCodeParam;
import com.caregiver.watch.business.user.service.AuthService;
import com.caregiver.watch.business.user.service.SmsService;
import com.caregiver.watch.common.config.SystemConfig;
import com.caregiver.watch.common.enums.SendSmsCodeEnum;
import com.caregiver.watch.common.exception.BaseException;
import com.caregiver.watch.common.exception.business.BusinessException;
import com.caregiver.watch.common.redis.service.RedisService;
import com.caregiver.watch.thirdparty.api.SmsApi;
import com.caregiver.watch.thirdparty.model.dto.SmsBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.caregiver.watch.common.constant.Constants.COLON;

/**
 * @Description: 短信服务
 * @Author 疆戟
 * @Date 2025/8/16 10:52
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private AuthService authService;
    @Autowired
    private SmsApi smsApi;
    @Autowired
    private SystemConfig systemConfig;


    @Override
    public Boolean sendSmsCode(SendSmsCodeParam param) {
        log.info("发送短信验证码：{}", param);
        String phone = param.getPhone();
        if (Objects.isNull(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        SendSmsCodeEnum sendSmsCodeType = param.getType();
        if (Objects.isNull(sendSmsCodeType)) {
            throw new BusinessException("发送短信验证码类型错误");
        }
        // 生成验证码
        String code = generateVerificationCode();
        smsApi.mobileQuery(phone, SmsBo.build(sendSmsCodeType.getOperate(), code, sendSmsCodeType.getExpire()));
        redisService.setCacheObject(sendSmsCodeType.getKey() + COLON + phone, code, sendSmsCodeType.getExpire(), TimeUnit.MINUTES);
        return Boolean.TRUE;
    }

    @Override
    public Boolean verifySmsCode(VerifySmsCodeParam param) {
        authService.validateSmsCode(param.getPhone(), param.getCode(), param.getType());
        return Boolean.TRUE;
    }

    /**
     * 生成验证码
     *
     * @return
     */
    private String generateVerificationCode() {
        if (systemConfig.isDev() || systemConfig.isTest()) {
            return "111111";
        }
        Random random = new Random();
        // 生成 100000 到 999999 之间的随机整数（包含边界）
        int code = random.nextInt(900000) + 100000;
        return String.valueOf(code);
    }
}
